const tabsStore = useStore.tabsStore();

// 关闭tab
export const closeTab = async (router: any, tab: any) => {
  // if (tab.meta && tab.meta.affix) {
  //   return;
  // }
  // tabsStore.delView(tab);
  // toLastView(router, tabsStore.visitedViews, tab);

  if (tab.meta && tab.meta.affix) return;

  const views = useStore.tabsStore().visitedViews as any[];
  const idx = views.findIndex((v) => v.path === tab.path);
  // 选择下一个优先，否则上一个，再否则最后一个
  const target = views[idx + 1] || views[idx - 1] || views[views.length - 1];

  if (target) {
    await router.push(target.fullPath || target.path);
  }

  // 路由切换完成后再删除，避免与 Tabs 的内部激活态竞态
  useStore.tabsStore().delView(tab);
};

// 关闭其他tabs
export const closeOthersTabs = (router: any, tab: any) => {
  router.push(tab);
  tabsStore.delOthersViews(tab);
};

// 关闭全部tabs
export const closeAllTabs = (router: any, tab: any) => {
  tabsStore.delAllViews();
  toLastView(router, tabsStore.visitedViews, tab);
};

// 跳转到最后一个tab
export const toLastView = (router: any, visitedViews: any[], view: any) => {
  const latestView = visitedViews.slice(-1)[0];
  if (latestView) {
    router.push(latestView.fullPath);
  } else {
    if (view.name === "Home") {
      router.replace({ path: "/redirect" + view.fullPath });
    } else {
      router.push("/admin");
    }
  }
};
